package com.webreport.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webreport.dao.SessionDao;
import com.webreport.exception.DaoException;
import com.webreport.exception.LoginException;
import com.webreport.exception.ManagerException;
import com.webreport.model.db.SessionMonitor;
import com.webreport.service.SessionManager;
import com.webreport.utils.JsonUtils;
import com.webreport.webapp.bean.LoginBean;

@Service("sessionManager")
public class SessionManagerImpl extends GenericManagerImpl<SessionMonitor, String> implements SessionManager {
	SessionDao dao;
	
	@Autowired
	public SessionManagerImpl(SessionDao dao) {
		super(dao);
		this.dao = dao;
	}
	
	public SessionMonitor querySession(String clientid) throws ManagerException {
		SessionMonitor session = null;
		try {
			session = this.dao.queryById(clientid);
		} catch (DaoException e) {
			log.error("查询Session失败" + e.getMessage());
		}
		
		return session;
	}
	
	public List<SessionMonitor> queryByUser(String username) throws ManagerException {
		try {
			return this.dao.queryByUsername(username);
		} catch (DaoException e) {
			log.error("查询Session失败" + e.getMessage());
			throw new ManagerException("session获取失败");
		}
	}
	
	public SessionMonitor insertSession(LoginBean login, String ip) throws ManagerException, LoginException {
		if (login.getMultilogin() != 0) {
			List<SessionMonitor> sessions = this.queryByUser(login.getUsername());
			if (sessions != null && sessions.size() >= login.getMultilogin()) {
				throw new LoginException("在线数大于该用户允许在线次数！");
			}
		}
		SessionMonitor session = new SessionMonitor();
		Date now = new Date();
		session.setLogintime(now);
		session.setEnabled(true);
		session.setUsername(login.getUsername());
		session.setUser(JsonUtils.toJson(login));
		session.setIp(ip);
		if (login.getExpiredays()>0)
			session.setExpiretime(DateUtils.addDays(now, login.getExpiredays()));
		String clientid;
		try {
			clientid = this.dao.insert(session);
		} catch (DaoException e) {
			log.error("保存session失败" + e.getMessage());
			throw new ManagerException("保存session失败");
		}
		session.setClientid(clientid);
		return session;
	}
	public void disableSession(String clientid) throws ManagerException{
		try {
			this.dao.disableSession(clientid);
		} catch (DaoException e) {
			log.error("disabled session失败" + e.getMessage());
			throw new ManagerException("删除session失败");
		}
	}
}
